package com.dyz.leetcode._19_greedy;

public class _670_maximumSwap {
    public int maximumSwap(int num) {
        char[] chars = String.valueOf(num).toCharArray();
        int len =  chars.length;

        int max = num;
        for (int i = 0; i < len; i++) {
            for (int j = i+1; j < len; j++) {
                swap(chars, i, j);
                max = Math.max(max,Integer.parseInt(new String(chars)));
                swap(chars, i, j);

            }
        }
        return max;

    }
    private void swap(char[] chars, int i, int j){
        char tmp = chars[i];
        chars[i] = chars[j];
        chars[j] = tmp;
    }

    public int maximumSwap1(int num) {
        char[] chars = String.valueOf(num).toCharArray();
        int [] last = new int[10];
        for(int i =0; i<chars.length; i++){
            last[chars[i]-'0'] = i;
        }

        for (int i = 0; i < chars.length; i++) {
            for(int d=9; d>chars[i]-'0'; d--){
                if(last[d]>i){
                    char tmp = chars[i];
                    chars[i]= chars[last[d]];
                    chars[last[d]]=tmp;
                    return Integer.parseInt(new String(chars));
                }
            }

        }
        return num;
    }
}
